package com.zgt.dao.impl;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.sun.xml.internal.org.jvnet.fastinfoset.RestrictedAlphabet;
import com.zgt.dao.TopicDao;
import com.zgt.model.Topic;

@Repository("topicDao")
public class TopicDaoImpl implements TopicDao {

	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Resource
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.hibernateTemplate = hibernateTemplate;
	}

	public void deleteTopicById(int id) {
		Topic topic = new Topic();
		topic.setId(id);
		hibernateTemplate.delete(topic);
	}

	public Topic getTopicById(int id) {
		return hibernateTemplate.get(Topic.class, id);
	}

	public void saveTopic(Topic topic) {
		hibernateTemplate.save(topic);
	}

	public void updateTopic(Topic topic) {
		hibernateTemplate.update(topic);
	}

	
	public boolean isExist(Topic Topic) {
		// TODO Auto-generated method stub
		return false;
	}

	public int getCount(String query) {
		List<Topic> topics = hibernateTemplate.find(query);
		return topics.size();
	}

	public List<Topic> listTopic(int pageStart, int pageSize) {
		List<Topic> topics = hibernateTemplate.findByCriteria(
				DetachedCriteria.forClass(Topic.class), pageStart, pageSize);
		return topics;
	}

	public void saveTopics(List list) {
		Iterator it = list.iterator();
		while (it.hasNext()) {
			hibernateTemplate.save(it.next());
		}
	}

	@SuppressWarnings("unchecked")
	public List<Topic> listSearch(final String query, final int start, final int size ) {
		List<Topic> topics = hibernateTemplate.executeFind(new HibernateCallback(){

			public Object doInHibernate(Session session)
					throws HibernateException, SQLException {
				return session.createQuery(query).setFirstResult(start).setMaxResults(size).list();
			}
			});
		return topics;
	}

	
}
